<?php
date_default_timezone_set("Asia/Shanghai");

echo "Handle Since ".date('Y-m-d H:i:s').PHP_EOL;

try {
    $queueDir = __DIR__ . '/../../queue';
    $filePattern = $queueDir . '/*.video.init';
    $tasks = glob($filePattern);
    if (empty($tasks)) {
        throw new Exception("No task to handle.");
    }

    $taskFile = $tasks[0];

    $taskFileName = pathinfo($taskFile, PATHINFO_BASENAME);
    if (!preg_match('/^(\w+)\.video.init$/', $taskFileName, $matches)) {
        throw new Exception("File Name Error : " . $taskFileName);
    }

    echo "Start handling " . $taskFileName . PHP_EOL;

    $hash = $matches[1];
    echo "Hash is " . $hash . PHP_EOL;

    $video_url = file_get_contents($taskFile);
    echo "Video URL: " . $video_url . PHP_EOL;
    if (empty($video_url)) {
        $deleted = unlink($taskFile);
        echo "Remove Empty Task: " . ($deleted ? 'done' : 'undone') . PHP_EOL;
        throw new Exception("Empty Video Request");
    }

    $done = rename($taskFile, $queueDir . '/' . $hash . '.video.doing');
    echo "Rename To Doing: " . ($done ? 'done' : 'undone') . PHP_EOL;

    $downloadedVideoDir = __DIR__ . '/../../data/' . $hash;
    $done = mkdir($downloadedVideoDir);
    echo "downloadedVideoDir: " . $downloadedVideoDir . " -> " . ($done ? 'done' : 'undone') . PHP_EOL;

    echo "Handle MARK 1 " . date('Y-m-d H:i:s') . PHP_EOL;

    $downloadedVideoFile = $downloadedVideoDir . '/origin.mp4';
    try {
        $commandForFetching = "wget -O " . escapeshellarg($downloadedVideoFile) . " " . escapeshellarg($video_url) . " 2>&1";
        echo "Running: " . $commandForFetching . PHP_EOL;
        exec($commandForFetching, $output, $returnVar);
        echo "Command Return: " . $returnVar . PHP_EOL;
        if ($returnVar == 0) {
            echo "Downloaded:" . PHP_EOL . implode(PHP_EOL, $output) . PHP_EOL;
        } else {
            throw new Exception("Error in download: " . PHP_EOL . implode(PHP_EOL, $output));
        }
    } catch (Exception $e1) {
        $done = rename($queueDir . '/' . $hash . '.video.doing', $queueDir . '/' . $hash . '.video.error');
        echo "Rename To Error: " . ($done ? 'done' : 'undone') . PHP_EOL;
        throw $e1;
    }

    echo "Handle MARK 2 " . date('Y-m-d H:i:s') . PHP_EOL;

    try {
        $commandForFFMpeg = "ffmpeg -i " . escapeshellarg($downloadedVideoFile)
            . " -c:v libx264 -c:a aac -strict -2 -f hls -hls_time 5 -hls_list_size 0 "
            . " " . escapeshellarg($downloadedVideoDir . "/playlist.m3u8");
        echo "Running: " . $commandForFFMpeg . PHP_EOL;
        exec($commandForFFMpeg, $output, $returnVar);
        echo "Command Return: " . $returnVar . PHP_EOL;
        if ($returnVar == 0) {
            echo "Transferred:" . PHP_EOL . implode(PHP_EOL, $output) . PHP_EOL;
            $done = rename($queueDir . '/' . $hash . '.video.doing', $queueDir . '/' . $hash . '.video.done');
            echo "Rename To Done: " . ($done ? 'done' : 'undone') . PHP_EOL;
        } else {
            throw new Exception("Error in transferred: " . PHP_EOL . implode(PHP_EOL, $output) );
        }
    }catch (Exception $e2)
    {
        $done = rename($queueDir . '/' . $hash . '.video.doing', $queueDir . '/' . $hash . '.video.error');
        echo "Rename To Error: " . ($done ? 'done' : 'undone') . PHP_EOL;
        throw $e2;
    }
}catch (Exception $exception){
    echo "ERROR: ". $exception->getMessage().PHP_EOL;
    echo $exception->getTraceAsString().PHP_EOL;
}

echo "Handle Ended ".date('Y-m-d H:i:s').PHP_EOL;